package com.example.study_manger.service;

import com.example.study_manger.entity.TrainingDocument;
import com.example.study_manger.repository.TrainingDocumentRe;
import com.example.study_manger.tools.OssOpe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DocumentService {
    @Autowired
    private TrainingDocumentRe documentRe;
    @Autowired
    private OssOpe ossOpe;

    public List<TrainingDocument> getAllDocuments(String type, Boolean underReview, Boolean published) {
        Specification<TrainingDocument> spec = Specification.where(null);
        // 动态添加查询条件
        if (type != null) {
            spec = spec.and((root, query, builder) -> builder.equal(root.get("type"), type));
        }
        if (underReview != null) {
            spec = spec.and((root, query, builder) -> builder.equal(root.get("underReview"), underReview));
        }

        if (published != null) {
            spec = spec.and((root, query, builder) -> builder.equal(root.get("published"), published));
        }
        // 执行查询
        return documentRe.findAll(spec);
    }

    public TrainingDocument addDocument(TrainingDocument document) {
        return documentRe.save(document);
    }

    public String deleteDocument(Long id) {
        try {
            TrainingDocument document= documentRe.findById(id).get();
            documentRe.deleteById(id);
            String url = document.getUrl();
            ossOpe.deleteFile(url);
            return "true";
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    public TrainingDocument updateDocument(Long id, TrainingDocument updatedDocument) {
        return documentRe.save(updatedDocument);
    }

    public TrainingDocument getDocuments(Long id) {
        return documentRe.findById(id).orElse(null);
    }
}
